package com.gdssoft.core.comparator;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;

public class ListComparator implements Comparator {

    public ListComparator() {}

    public ListComparator(String methodName) {
        this.methodName = methodName;
    }

    //空:普通的数据类型 非空:对象数据类型 取methodName返回值比较
    String methodName;
    
    public Object getValue(Object bean, String methodName) throws Exception {
        Method getMethod = bean.getClass().getMethod(methodName, null);
        return getMethod.invoke(bean, null);
    }

    public int compare(Object obj1, Object obj2) {
        int val = -1;
        try {
            if ( methodName == null ) {
                val = _compare(obj1, obj2);
            } else {
                val = _compare(getValue(obj1, methodName), getValue(obj2, methodName));
            }
        } catch (Exception ex) {ex.printStackTrace();}
        return val;
    }

    public int _compare(Object obj1, Object obj2) throws Exception {
        if ( obj1 == null || obj2 == null ) return obj1 == null ? -1 : 1;
        Class cl = obj1.getClass();
        if ( obj1 instanceof java.lang.Comparable ) {
        //byte int long float..number, date , boolean , char
            Method getMethod = obj1.getClass().getMethod("compareTo", new Class[]{cl});
            return (Integer) getMethod.invoke(obj1, new Object[]{obj2});
        }
        return -1;
    }

}